package com.example.testmap.models.parseur;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.codehaus.jackson.JsonFactory;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.JsonParser;
import org.codehaus.jackson.JsonToken;
import org.codehaus.jackson.map.JsonMappingException;


import android.os.AsyncTask;
import android.os.Environment;

import com.example.testmap.models.Bicloo;
import com.example.testmap.util.Util;

public class DonneeBicloo extends AsyncTask<Void, Void, Void> {

	protected Void doInBackground(Void... arg0) {

		List<Bicloo> listBicloo = new ArrayList<Bicloo>();
		try {

			URL url = new URL(
					"https://api.jcdecaux.com/vls/v1/stations?contract=Nantes&apiKey=58593190c2b20d324aa4186546e0eb9f51f378d9");
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setRequestMethod("GET");
			conn.setRequestProperty("Accept", "application/json");

			if (conn.getResponseCode() != 200) {
				throw new RuntimeException("Failed : HTTP error code : "
						+ conn.getResponseCode());
			}

			BufferedReader br = new BufferedReader(new InputStreamReader(
					(conn.getInputStream())));

			String output;
			System.out.println("Output from Server .... \n");
			String retour = "";
			while ((output = br.readLine()) != null) {
				retour = retour + output;
			}

			try {
				File root = createFile();
				writeFile(retour, root);
			} catch (IOException e) {
				e.printStackTrace();
			}

			conn.disconnect();
		} catch (MalformedURLException e) {

			e.printStackTrace();

		} catch (IOException e) {

			e.printStackTrace();
		}

		readFileJson(listBicloo);

		return null;
	}

	private void readFileJson(List<Bicloo> listBicloo) {
		try {
			double lat = 0;
			double lng = 0;
			String nomStation = "";

			JsonFactory jfactory = new JsonFactory();

			/*** read from file ***/
			JsonParser jParser = jfactory.createJsonParser(new File(Environment
					.getExternalStorageDirectory() + "/Notes/Nantes.json"));

			// loop until token equal to "}"
			while (jParser.nextToken() != JsonToken.END_ARRAY) {

				String fieldname = jParser.getCurrentName();
				if ("name".equals(fieldname)) {
					jParser.nextToken();
					nomStation = jParser.getText();
				} else if ("lat".equals(fieldname)) {
					jParser.nextToken();
					lat = jParser.getDoubleValue();
				} else if ("lng".equals(fieldname)) {
					jParser.nextToken();
					lng = jParser.getDoubleValue();
				}

				System.out.println("name" + nomStation);

				if (!Util.getStationsbiclooList().containsKey(nomStation)) {
					Bicloo bicloo = new Bicloo(nomStation, lat, lng);
					Util.getStationsbiclooList().put(nomStation, bicloo);
				}

				System.out.println("sizefffffff"
						+ Util.getStationsbiclooList().size());

			}

			jParser.close();
			System.out.println("\n");
		} catch (JsonGenerationException e) {

			e.printStackTrace();

		} catch (JsonMappingException e) {

			e.printStackTrace();

		} catch (IOException e) {

			e.printStackTrace();

		}
	}

	private void writeFile(String retour, File root) throws IOException {
		File gpxfile = new File(root, "Nantes.json");
		FileWriter writer = new FileWriter(gpxfile);
		writer.append(retour);
		writer.flush();
		writer.close();
	}

	private File createFile() {
		File root = new File(Environment.getExternalStorageDirectory(), "Notes");
		if (!root.exists()) {
			root.mkdirs();
		}
		return root;
	}

}
